package cn.minicloud;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ProxyFrontendHandler extends ChannelInboundHandlerAdapter {
    private final Channel backendChannel;

    public ProxyFrontendHandler(Channel backendChannel) {
        this.backendChannel = backendChannel;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (backendChannel.isActive()) {
            backendChannel.writeAndFlush(msg);
        } else {
            ((ByteBuf) msg).release();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        if (backendChannel.isActive()) {
            backendChannel.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
        if (backendChannel.isActive()) {
            backendChannel.close();
        }
    }
}
